package dynamic.mybatisplus.core;


import dynamic.ibatis.binding.DMapperRegistry;
import dynamic.ibatis.session.DConfiguration;
import dynamic.ibatis.session.DSqlSession;
import dynamic.metadata.EntityClass;
import dynamic.mybatisplus.core.override.MybatisMapperProxyFactory;
import org.apache.ibatis.binding.BindingException;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 继承至MapperRegistry
 *
 * @author Caratacus hubin
 * @since 2017-04-19
 */
public class DMybatisMapperRegistry extends DMapperRegistry {

    private final DConfiguration config;

    private final Map<Class<?>,Map<EntityClass, MybatisMapperProxyFactory<?>>> knownMappers = new HashMap<>();


    public DMybatisMapperRegistry(DConfiguration config) {
        super(config);
        this.config = config;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T getMapper(Class<T> type, EntityClass entityClass, DSqlSession sqlSession) {
        // TODO 这里换成 MybatisMapperProxyFactory 而不是 MapperProxyFactory
        // fix https://github.com/baomidou/mybatis-plus/issues/4247
        final Map<EntityClass,MybatisMapperProxyFactory<?>> map = knownMappers.get(type);
        if (map == null) {
            throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
        }

        MybatisMapperProxyFactory<T> mapperProxyFactory = (MybatisMapperProxyFactory<T>) map.get(entityClass);
        try {
            return mapperProxyFactory.newInstance(sqlSession);
        } catch (Exception e) {
            throw new BindingException("Error getting mapper instance. Cause: " + e, e);
        }
    }

    @Override
    public <T> boolean hasMapper(Class<T> type,EntityClass entityClass) {
        return knownMappers.containsKey(type)&&knownMappers.get(type).containsKey(entityClass);
    }

    /**
     * 清空 Mapper 缓存信息
     */
    protected <T> void removeMapper(Class<T> type,EntityClass entityClass) {
        if(hasMapper(type,entityClass)){
            knownMappers.get(type).remove(entityClass);
            if (knownMappers.get(type).isEmpty()){
                knownMappers.remove(type);
            }
        }
    }

    @Override
    public <T> void addMapper(Class<T> type,EntityClass entityClass) {
        if (type.isInterface()) {
            if (hasMapper(type,entityClass)) {
                // TODO 如果之前注入 直接返回
                return;
                // TODO 这里就不抛异常了
//                throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
            }
            boolean loadCompleted = false;
            try {
                // TODO 这里也换成 MybatisMapperProxyFactory 而不是 MapperProxyFactory
                if(!knownMappers.containsKey(type)){
                    knownMappers.put(type,new HashMap<EntityClass,MybatisMapperProxyFactory<?>>());
                }
                knownMappers.get(type).put(entityClass,new MybatisMapperProxyFactory<>(type));
                // It's important that the type is added before the parser is run
                // otherwise the binding may automatically be attempted by the
                // mapper parser. If the type is already known, it won't try.
                // TODO 这里也换成 MybatisMapperAnnotationBuilder 而不是 MapperAnnotationBuilder
                DMybatisMapperAnnotationBuilder parser = new DMybatisMapperAnnotationBuilder(config, type, entityClass);
                parser.parse();
                loadCompleted = true;
            } finally {
                if (!loadCompleted) {
                    knownMappers.remove(type);
                }
            }
        }
    }

    /**
     * 使用自己的 knownMappers
     */
    @Override
    public Collection<Class<?>> getMappers() {
        return Collections.unmodifiableCollection(knownMappers.keySet());
    }

}

